<?php

namespace App\Services;

use App\Models\Order;
use App\Models\OrderComment;
use App\Models\OrderServiceSystemSign;
use App\Models\Receipt;
use App\Models\ReceiptInfo;
use App\Models\SmsLog;
use App\Support\Data;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;

class UserService
{

    /**
     * 获取用户订单统计数量
     *
     * @Author hechengwei
     * @email chichiooo@sina.com
     * @DateTime 2024-03-12
     * @param [type] $userid
     * @return void
     */
    public static function getUserOrderStatistics($userid)
    {
        $orderCount = Order::where('user_id', $userid)->get();
        // 全部订单
        $amount_order = $orderCount->count() ?? 0;
        // 服务中订单
        $orderServiceNum = $orderCount->where('order_status', 1)->count() ?? 0;
        // 已完成订单
        $orderCompletedNum = $orderCount->where('order_status', 2)->count() ?? 0;
        // 已评价订单
        $orderEvalNum = $orderCount->where('order_status', 2)->where('is_eval', 1)->count() ?? 0;
        return ['all_orders' => $amount_order, 'orders_in_service' => $orderServiceNum, 'completed_order' => $orderCompletedNum, 'evaluated_orders' => $orderEvalNum];
    }

    /**
     * 邮箱账户
     *
     * @Author hechengwei
     * @email chichiooo@sina.com
     * @DateTime 2024-03-12
     * @param [type] $userid
     * @return void
     */
    public static function getUserOrderEmail($userid)
    {
        $order = Order::with(['serviceEmail' => function ($query) {
            $query->select('id', 'order_id', 'email', 'password');
        }])->where('user_id', $userid)->select('id', 'user_id')->get();
        $email = [];
        foreach ($order as $key => $val) {
            array_push($email, $val->serviceEmail);
        }
        return $email;
    }
    /**
     * 系统注册信息
     *
     * @Author hechengwei
     * @email chichiooo@sina.com
     * @DateTime 2024-03-12
     * @param [type] $userid
     * @return void
     */
    public static function getUserOrderSystemRegister($userid)
    {
        $order = Order::with(['serviceSystem' => function ($query) {
            $query->select('id', 'order_id', 'system_name', 'website', 'email', 'password');
        }])->where('user_id', $userid)->select('id', 'user_id')->get();
        $email = [];
        foreach ($order as $key => $val) {
            array_push($email, $val->serviceSystem);
        }
        return $email;
    }

    /**
     * 系统注册信息
     *
     * @Author hechengwei
     * @email chichiooo@sina.com
     * @DateTime 2024-03-12
     * @param [type] $userid
     * @return void
     */
    public static function getUserOrderSystemRegisterPaginate($userid, $page, $limit)
    {
        // $order = Order::with(['serviceSystem' => function ($query) {
        //     $query->select('id', 'order_id', 'system_name', 'website', 'email', 'password');
        // }])->where('user_id', $userid)->select('id', 'user_id')->paginate($limit);
        $orderId = Order::where('user_id', $userid)->pluck('id')->toArray();

        if (!empty($orderId)) {
            $systemInfo = OrderServiceSystemSign::where('order_id', $orderId)->select('id', 'order_id', 'system_name', 'website', 'email', 'password')->paginate($limit);
        }


        // dd($systemInfo);

        // $email = [];
        // foreach ($order as $key => $val) {
        //     // array_push($email, $val->serviceSystem->toArray());
        //     $email = $val->serviceSystem;
        // }
        // dd($email);
        return $systemInfo ?? [];
    }
    /**
     * 近期订单
     *
     * @Author hechengwei
     * @email chichiooo@sina.com
     * @DateTime 2024-03-12
     * @param [type] $userid
     * @return void
     */
    public static function getUserRecentOrderList($userid)
    {
        $order = Order::where('user_id', $userid)
            ->select('id', 'order_sn', 'order_status', 'order_amount', 'service', 'created_at')
            ->limit(5)
            ->orderBy('created_at', 'desc')
            ->get();
        foreach ($order as $key => &$val) {
            $val['service'] = Data::getOrderServiceById($val['service']);
        }
        return $order ?? [];
    }

    /**
     * 近期订单
     *
     * @Author hechengwei
     * @email chichiooo@sina.com
     * @DateTime 2024-03-12
     * @param [type] $userid
     * @return void
     */
    public static function getUserRecentOrderListPaginate($userid, $page, $limit)
    {
        $order = Order::where('user_id', $userid)
            ->select('id', 'order_sn', 'order_status', 'order_amount', 'service', 'created_at')
            // ->limit(5)
            ->orderBy('created_at', 'desc')
            ->paginate($limit);
        foreach ($order as $key => &$val) {
            $val['service'] = Data::getOrderServiceById($val['service']);
        }
        return $order;
    }


    /**
     * 订单列表
     *
     * @Author hechengwei
     * @email chichiooo@sina.com
     * @DateTime 2024-03-14
     * @param [type] $userid
     * @return void
     */
    public static function getUserOrderList($userid,  $where = [], $fields = ['*'], $limit = 10)
    {
        $where = function ($query) use ($where) {
            if (isset($where['order_status']) && $where['order_status'] != '') {
                $query->where('order_status', $where['order_status']);
            }

            if (isset($where['datetime']) && $where['datetime'] != '') {
                $query->whereDate('created_at', $where['datetime']);
            }
        };
        $order = Order::with(['orderService' => function ($query) {
            $query->select('order_id', 'full_report');
        }, 'polish', 'profiles'])->where('user_id', $userid)
            ->where($where)
            ->select($fields)
            ->orderBy('created_at', 'desc')
            ->paginate($limit);

        foreach ($order as $key => &$val) {
            $val['service'] = Data::getOrderServiceById($val['service']);
        }
        return $order ?? [];
    }

    /**
     * 获取订单详情
     *
     * @Author hechengwei
     * @email chichiooo@sina.com
     * @DateTime 2024-03-14
     * @param [type] $id
     * @return void
     */
    public static function getOrderDetail($id)
    {
        $orderDetail = Order::with(['orderService', 'report', 'syntax', 'details', 'polish', 'profiles', 'serviceSystem'])
            ->where('id', $id)
            ->select('id', 'order_sn', 'created_at', 'order_status', 'pay_amount', 'pay_ticket', 'pay_type', 'pay_status', 'pay_datetime', 'service', 'language', 'manuscript', 'reference_file', 'additional', 'purpose', 'purpose as purpose_text', 'subject_area', 'subject_area as subject_area_text', 'discipline', 'discipline as discipline_text', 'is_carefree', 'is_eval')
            ->first();

        if (!empty($orderDetail)) {
            if (isset($orderDetail->service) && !empty($orderDetail->service)) {
                $orderDetail->service = Data::getOrderServiceById($orderDetail->service);
            }

            if (isset($orderDetail->manuscript) && !empty($orderDetail->manuscript)) {
                $orderDetail->manuscript = json_decode($orderDetail->manuscript, true);
            }

            if (isset($orderDetail->reference_file) && !empty($orderDetail->reference_file)) {
                $orderDetail->reference_file = explode(',', $orderDetail->reference_file);
            }
        }
        $schedule = $orderDetail->serviceSystem->pluck('schedule');
        if (!empty($schedule)) {
            $arr = [];
            foreach ($schedule as $val) {
                $arr = json_decode($val, true);
            }
            foreach ($arr as $key => &$val) {
                if (isset($val['submit_reg_files']) && !empty($val['submit_reg_files'])) {
                    $val['submit_reg_files'] = config('filesystems.disks.qiniu.domains.https') . $val['submit_reg_files'];
                } else {
                    $val['submit_reg_files'] = '';
                }
            }
            $orderDetail->submission_progress = $arr;
            $orderDetail->toArray();
            unset($orderDetail['serviceSystem']);
        }
        // dd(array_column($orderDetail['serviceSystem']->toArray(), 'schedule'));
        return $orderDetail ?? [];
    }


    /**
     * 修改手机号
     *
     * @Author hechengwei
     * @email chichiooo@sina.com
     * @DateTime 2024-03-14
     * @param [type] $user
     * @param [type] $payload
     * @return void
     */
    public static function modifyUserPhone($user, $payload)
    {
        $user->username = $payload['phone'];
        $user->phone = $payload['phone'];
        if ($user->save()) {
            SmsLog::use_code($payload['code'], $payload['phone']);
            return true;
        } else {
            return false;
        }
    }


    /**
     * 修改订单状态
     *
     * @Author hechengwei
     * @email chichiooo@sina.com
     * @DateTime 2024-03-14
     * @param [type] $orderId
     * @param integer $status
     * @return void
     */
    public static function modifyOrderStatus($orderId, $status = 0)
    {
        return Order::where('id', $orderId)->update(['order_status' => $status]);
    }


    /**
     * 评价订单
     *
     * @Author hechengwei
     * @email chichiooo@sina.com
     * @DateTime 2024-03-14
     * @param [object] $user
     * @param [array] $comment
     * @return void
     */
    public static function evaluateOrder($user, $comment)
    {
        $comment = [
            'order_id' => $comment['order_id'] ?? 0,
            'user_id' => $user->id ?? 0,
            'username' => $user->username ?? '',
            'nickname' => $user->nickname ?? '',
            'phone' => $user->phone ?? '',
            'organization' => $user->institution ?? '',
            'status' => 0,
            'journal_name' => $comment['journal_name'] ?? '',
            'journal_area' => $comment['journal_area'] ?? '',
            'title' => $comment['title'] ?? '',
            'title_href' => $comment['title_href'] ?? '',
            'cover_page' => $comment['cover_page'] ?? '',
            'content' => $comment['content'] ?? '',
        ];

        $result = OrderComment::updateOrCreate(['order_id' => $comment['order_id'], 'user_id' => $user->id], $comment);

        return $result ? true : false;
    }


    /**
     * 近期订单
     *
     * @Author hechengwei
     * @email chichiooo@sina.com
     * @DateTime 2024-03-12
     * @param [type] $userid
     * @return void
     */
    public static function getRectiptInfoListPaginate($userid, $page, $limit)
    {
        $receiptInfoList = ReceiptInfo::where('user_id', $userid)
            ->select('id', 'user_id', 'is_default', 'type', 'type as type_text', 'header', 'company_addr', 'company_phone', 'bank_name', 'bank_number', 'tax_type', 'tax_type as tax_type_text', 'tax_user_id', 'receive_mobile', 'created_at')
            // ->limit(5)
            ->orderBy('created_at', 'desc')
            ->paginate($limit);
        return $receiptInfoList ?? [];
    }


    /**
     * 获取申请开票信息
     *
     * @Author hechengwei
     * @email chichiooo@sina.com
     * @DateTime 2024-06-05
     * @param [type] $userid
     * @return void
     */
    public static function getReceiptInfo($userid)
    {
        $orderList = Order::where(['user_id' => $userid, 'order_status' => 2])->select('id', 'order_sn', 'created_at', 'pay_amount', 'service', 'order_status', 'order_status as order_status_text', 'is_receipt')->get();
        if (!empty($orderList)) {
            foreach ($orderList as $key => &$val) {
                $val['service'] = Data::getOrderServiceById($val['service']);
            }
        }

        $receiptInfo = ReceiptInfo::where(['user_id' => $userid, 'is_default' => 1])->select('*', 'type as type_text', 'tax_type as tax_type_text')->first();
        return ['orderList' => $orderList, 'receiptInfo' => $receiptInfo];
    }


    /**
     * 提交申请开票信息
     *
     * @Author hechengwei
     * @email chichiooo@sina.com
     * @DateTime 2024-06-05
     * @param [type] $data
     * @param [type] $userid
     * @return void
     */
    public static function applyReceipt($data, $userid)
    {
        $receiptInfo = ReceiptInfo::find($data['receipt_info_id']);
        if (!empty($receiptInfo)) {
            $receipt = [
                'user_id' => $userid,
                'order_id' => $data['order_id'],
                'receipt_info_id' => $data['receipt_info_id'],
                'total_money' => $data['total_money'],
                'type' => $receiptInfo['type'],

                'header' => $receiptInfo['header'],
                'company_addr' => $receiptInfo['company_addr'],
                'company_phone' => $receiptInfo['company_phone'],
                'bank_name' => $receiptInfo['bank_name'],
                'bank_number' => $receiptInfo['bank_number'],
                'tax_type' => $receiptInfo['tax_type'],
                'tax_user_id' => $receiptInfo['tax_user_id'],
                'tax_cert' => $receiptInfo['tax_cert'],
                'receive_user' => $receiptInfo['receive_user'],
                'receive_mobile' => $receiptInfo['receive_mobile'],
                'receive_addr' => $receiptInfo['receive_addr'],
                'remark' => $receiptInfo['remark'],
            ];
            DB::beginTransaction();
            try {
                $result =  Receipt::create($receipt);
                Order::whereIn('id', explode(',', $data['order_id']))->update(['is_receipt' => 1]);
                DB::commit();
                return success();
            } catch (\Exception $e) {
                Log::error('申请开票错误' . json_encode($e));
                DB::rollBack();
                return fail_message();
            }
        } else {
            return fail_message('申请失败');
        }
    }

    /**
     * 发票记录
     *
     * @Author hechengwei
     * @email chichiooo@sina.com
     * @DateTime 2024-06-05
     * @param [type] $userid
     * @param [type] $page
     * @param [type] $limit
     * @return void
     */
    public static function getReceiptList($userid, $page, $limit)
    {
        $receiptList = Receipt::where('user_id', $userid)
            ->select('id', 'user_id', 'receipt_info_id', 'order_id', 'status', 'total_money', 'express_name', 'express_number', 'express_img', 'created_at', 'type', 'type as type_text', 'header', 'receipt_file')
            // ->limit(5)
            ->orderBy('created_at', 'desc')
            ->paginate($limit);

        return $receiptList ?? [];
    }


    /**
     * 发票详情
     *
     * @Author hechengwei
     * @email chichiooo@sina.com
     * @DateTime 2024-06-07
     * @param [type] $id
     * @return void
     */
    public static function getReceiptDetail($id)
    {
        $detail = Receipt::where('id', $id)->first();
        $order = Order::whereIn('id', explode(',', $detail->order_id))->select('id', 'order_sn', 'created_at', 'pay_amount', 'service', 'order_status', 'order_status as order_status_text')->get();
        if (!empty($order)) {
            foreach ($order as $key => &$val) {
                $val['service'] = Data::getOrderServiceById($val['service']);
            }
        }
        return ['detail' => $detail, 'orderList' => $order];
    }


    public static function getEvalList($userid, $payload)
    {
        $where = function ($query) use ($payload) {
            if (isset($payload['order_status']) && $payload['order_status'] != '') {
                $query->where('order_status', $payload['order_status']);
            }

            if (isset($payload['created_at']) && $payload['created_at'] != '') {
                $query->whereDate('created_at', $payload['created_at']);
            }
        };
        // $evalList = OrderComment::with(['order' => function ($query) use ($where) {
        //     $query->where($where)->select('id', 'order_sn', 'created_at', 'order_status', 'order_amount', 'pay_amount', 'service');
        // }])->where('user_id', $userid)->where('status', 1)
        //     ->select('id', 'user_id', 'order_id', 'journal_name', 'journal_area', 'title', 'title_href', 'cover_page', 'content')
        //     // ->limit(5)
        //     ->orderBy('created_at', 'desc')
        //     ->paginate($payload['limit']);
        // foreach ($evalList as $key => &$val) {
        //     $val->order['service_name'] = Data::getOrderServiceById($val->order['service']);
        // }


        $evalList = Order::with(['orderComment' => function ($query) use ($where) {
            $query->where('status', 1)->select('id', 'user_id', 'order_id', 'journal_name', 'journal_area', 'title', 'title_href', 'cover_page', 'content');
        }])->where('user_id', $userid)
            ->where($where)
            ->select('id', 'order_sn', 'created_at', 'order_status', 'order_amount', 'pay_amount', 'service')
            // ->limit(5)
            ->orderBy('created_at', 'desc')
            ->paginate($payload['limit']);
        foreach ($evalList as $key => &$val) {
            $val['service_name'] = Data::getOrderServiceById($val['service']);
        }

        return $evalList ?? [];
    }
}
